package com.tl.demo;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRow;

import cn.com.zprk.XsdUtil;
import cn.com.zprk.xsd.Tables;

@SuppressWarnings("all")
public class XWPFUtil {
	private static final Logger log = Logger.getLogger(ZPDAO.class);
	
	private static String path = "";
	static{
		String file = "cn/com/zp/" + PublicConf.JLXZ_TEMPLATE_NAME;
		path = XWPFUtil.class.getClassLoader().getResource(file).getPath();
	}
	
	/**
	 * 生成word
	 * @author tl
	 * @param userMap
	 * @param wordMap
	 * @throws Exception
	 * @time 2014-12-24
	 */
	public static XWPFDocument generateWord(Map<String, Object> userMap,Map<String, List<Map<String, String>>> wordMap) throws Exception{
		BufferedOutputStream bos = null;
		try {
			XWPFDocument docTemp = new XWPFDocument(POIXMLDocument.openPackage(path));
			Iterator<XWPFTable> it = docTemp.getTablesIterator();
			XWPFTable table = it.next();	//因为总共才一个表格
			
			//记住要复制的行
			CTRow ctRow0 = null;
			CTRow ctRow1 = null;
			
			//替换模板值
			int rowCount = table.getNumberOfRows();
			for(int i=0;i<rowCount;i++){
				XWPFTableRow row = table.getRow(i);
				String text = row.getCell(0).getText();	//获取第一列的值
				
				//标题的值另外替换
				if(i==0){
					text = text.substring(0,2);
					if(userMap.containsKey(text)){
						Object obj = userMap.get(text);
						String val = obj!=null ? obj.toString() : "";
						
						replaceCell(row.getCell(0),val,true);
						continue;
					}
				}
				
				if(text.contains(PublicConf.WORD_TITLE)){
					//记住要增加的行
					ctRow0=(CTRow) row.getCtRow().copy();
					continue;
				}
				
				if(text.contains(PublicConf.WORD_TD1)){
					//记住要增加的另外的一行
					ctRow1=(CTRow) row.getCtRow().copy();
					continue;
				}
				
				List<XWPFTableCell> cells = row.getTableCells();
				for(XWPFTableCell c :cells){
					String txt = c.getText();
					txt = StringUtils.trim(txt);
					if(userMap.containsKey(txt)){
						Object obj = userMap.get(txt);
						String val = obj!=null ? obj.toString() : "";
						replaceCell(c,val,false);
					}
				}
			}
			//删除倒数两行
			table.removeRow(rowCount-1);
			table.removeRow(rowCount-2);
			
			XWPFTableRow row0  = null;
			XWPFTableRow row1 = null;
			
			//添加新行新数据
			for(Map.Entry<String,List<Map<String, String>>> entry:wordMap.entrySet()){
				String key = entry.getKey();
				Map<String, String> jlMap = PublicConf.jlMap.get(0);
				key = jlMap.get(key);
				List<Map<String, String>> list = entry.getValue();
				row0=new XWPFTableRow(ctRow0,table);
				replaceCell(row0.getCell(0), key,true);
				table.addRow(row0);
				
				for(Map<String,String> map:list){
					for(Map.Entry<String, String> valEntry:map.entrySet()){
						String key2 = valEntry.getKey();
						String val = valEntry.getValue();
						row1=new XWPFTableRow(ctRow1,table);
						replaceCell(row1.getCell(0), key2,false);
						replaceCell(row1.getCell(1), val,false);
						table.addRow(row1);
					}
				}
			}
			return docTemp;
		
//			String fileName = uuid +".doc";
//			fileName = path+fileName;
//			bos = new BufferedOutputStream(new FileOutputStream(fileName));
//			docTemp.write(bos);
//			bos.flush();
//			log.info("简历已生成---------------------------------------------------"+uuid);
		} catch (Exception e) {
			throw new Exception(e.fillInStackTrace());
		}finally{
			try {
				if(bos!=null){
					bos.close();
				}
			} catch (IOException e) {
				log.error(e.fillInStackTrace());
			}
		}
	}
	
	private final static String RUN_COLOR="Color";
	private final static String RUN_FONTSIZE="FontSize";
	private final static String RUN_Subscript="Subscript";
	private final static String RUN_Underline="Underline";
	private final static String RUN_FontFamily="FontFamily";
	private final static int RUN_SIZE = 9;
	private final static double RUN_FOND_SIZE = 10.5;
	private final static String RUN_FONT_NAME = "宋体";
	
	public static Map getRunStyle(XWPFRun runOld) {
		Map mapAttr = new HashMap();
		mapAttr.put(RUN_COLOR, runOld.getColor());
		if (-1 == runOld.getFontSize()) {
			mapAttr.put(RUN_FONTSIZE, 12);
		} else {
			mapAttr.put(RUN_FONTSIZE, runOld.getFontSize());
		}
		mapAttr.put(RUN_Subscript, runOld.getSubscript());
		mapAttr.put(RUN_Underline, runOld.getUnderline());
		mapAttr.put(RUN_FontFamily, runOld.getFontFamily());
		return mapAttr;
	}
	
	public static XWPFRun setRunStyle(XWPFRun runNew, Map styleMap,String val,boolean isBold) {
		if(styleMap==null){
			runNew.setFontFamily(RUN_FONT_NAME);
			runNew.setFontSize(RUN_SIZE);
		}else{
			if ("-1".equals(styleMap.get(RUN_FONTSIZE).toString())) {//处理小四字号读取为-1的问题
				runNew.setFontSize(RUN_SIZE);
			} else {
				runNew.setFontSize((Integer) styleMap.get(RUN_FONTSIZE));
			}
			runNew.setColor((String) styleMap.get(RUN_COLOR));
			runNew.setUnderline((UnderlinePatterns) styleMap.get(RUN_Underline));
			runNew.setSubscript((VerticalAlign) styleMap.get(RUN_Subscript));
			runNew.setFontFamily((String) styleMap.get(RUN_FontFamily));
		}
		runNew.setBold(isBold);
		runNew.setText(val);
		return runNew;
	}
	
	private static void replaceCell(XWPFTableCell c,String val,boolean isBold){
		if(c.getParagraphs().size()>0){
			XWPFParagraph xp = c.getParagraphs().get(0);
			List<XWPFRun> runs = xp.getRuns();
			Map styleMap = null;
			for(int i=0;i<runs.size();i++){
				String text = runs.get(i).getText(0);
				if(StringUtils.isNotBlank(text)){
					styleMap = getRunStyle(runs.get(i));
				}
				xp.removeRun(i);
			}
			XWPFRun run = xp.insertNewRun(0);
			setRunStyle(run,styleMap,val,isBold);
		}
	}
	
	
	/*private static void replaceCell(XWPFTableCell c, String val,boolean isBold) throws Exception, IOException {
		if(c.getParagraphs().size()>0){
			c.removeParagraph(0);
			XWPFParagraph np = new XWPFParagraph(c.getCTTc().addNewP(),c);
			XWPFRun run = np.createRun();
			np.setVerticalAlignment(TextAlignment.AUTO);
			np.setAlignment(ParagraphAlignment.MEDIUM_KASHIDA);				//内容居中显示
			run.getCTR().addNewRPr().addNewColor().setVal("FF0000");		//FF0000红色
			run.setUnderline(UnderlinePatterns.THICK);						//加粗
			run.setText(val); 
		}
	}*/
	
	public static void main(String[] args) throws Exception {
		ZPDAO dao = new ZPDAO();
		System.out.println(path);
//		dao.generateWord("U9jshWZy44bPHWyBzdeVvf","1111111");
	}
	
}
